<?php
namespace Index\Controller;
use Think\Controller;
class LoginController extends CommonController {
    public function index(){
        // layout(false);
    	if(isset($_SESSION['uid'])){
    		$this->error('你已经登录',U('index/user/index'));
    	}
       //随机获取一条问题
    	$question = D('vercode')->getOne();
        //分配变量
    	$this->assign('question',$question);
        //载入视图
        $this->assign('title',"登录");
        $this->display();
    }
    public function login()
    {
    	// var_dump(I('post.'));
    	//判断人类验证
    	D('vercode')->checkCode(I('post.vercode'));

    	$email = I('post.email');

    	$password = md5(I('post.pass'));

    	$res = M('user')->where("email='$email' and password='$password'")->find();

    	if($res){
            if($res['status']==1){
                ReAjax(1,"用户被封，请联系管理员");
            }
    		$_SESSION['uid']=$res['id'];
    		$_SESSION['nickname']=$res['nickname'];
            if($res['face']){
                $_SESSION['face']=__ROOT__.$res['face'];
            }else{
                $_SESSION['face']=$res['qqface'];
            }
            
			ReAjax(0,"登录成功");
    	}else{
    		ReAjax(1,"邮箱或者密码错误");
    	}

    }

    public function out()
    {
    	session_unset();
    	session_destroy();
    	$this->success('退出成功', U('index/index/index'));
    }


    public function qqlogin()
    {
        qqlogin();
    }

    public function qqreturn()
    {
        $openid = getOpenId();

        $res = M('user')->where("openid='$openid'")->find();

        if($res){
            $_SESSION['uid']=$res['id'];
            $_SESSION['nickname']=$res['nickname'];
            if($res['face']){
                $_SESSION['face']=__ROOT__.$res['face'];
            }else{
                $_SESSION['face']=$res['qqface'];
            }
            $this->success('登录成功',U('index/user/index'));
        }else{
            $userinfo = getUserInfo();
            $data['nickname'] =  $userinfo['nickname'];
            $data['sex'] =  $userinfo['gender'];
            $data['openid'] =  $openid;
            $data['city'] =  $userinfo['city'];
            $data['create_time'] = time();
            $data['face']='';
            $data['qqface']=$userinfo['figureurl_2'];

            if($id =M('user')->add($data)){
                $_SESSION['uid']=$id;
                $_SESSION['nickname']=$data['nickname'];
                $_SESSION['face']=$data['qqface'];
                $this->success('登录成功',U('index/user/index'));
            }
        }
    }

    public function getcity()
    {
        $ip = "121.33.61.243";

        $url = "http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;

        $data = file_get_contents($url);

        var_dump(json_decode($data,true));

        var_dump($_SERVER);
    }
}